//
//  ConfigBluetoothViewController.m
//  PPScaleDemo
//
//  Created by 彭思远 on 2021/3/11.
//

#import "BindingEquipmentViewController.h"
#import "ConfigNetworkViewController.h"

@interface BindingEquipmentViewController ()<PPDataInterface, PPBleStateInterface>
@property (weak, nonatomic) IBOutlet UILabel *currentWeightLabel;
@property (weak, nonatomic) IBOutlet UILabel *connectStateLabel;

@property (nonatomic, strong) PPScaleManager *scaleManager;
@property (nonatomic, strong) UserModel *currentUser;
@end

@implementation BindingEquipmentViewController

+ (instancetype)instance{
    return [[UIStoryboard storyboardWithName:@"Main" bundle:nil] instantiateViewControllerWithIdentifier:@"BindingEquipmentViewController"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"Binding equipment";
    [self newSearch];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.scaleManager disconnect];
}




- (void)newSearch{
    self.currentUser = [IdentityManager manager].currentUser;
    PPUserModel *userModel = [[PPUserModel alloc] initWithUserHeight:self.currentUser.userHeight gender:self.currentUser.userGender age:self.currentUser.userAge andUnit:self.currentUser.userUnit];
    self.scaleManager = [[PPScaleManager alloc] initWithMacAddressList:nil filterDeviceNameArr:nil andUserModel:userModel];
    self.scaleManager.stateInterface = self;
    self.scaleManager.dataInterface = self;
    [self.scaleManager startSearching];

}

/// 监听秤发出的过程数据
- (void)scaleManager:(PPScaleManager *)manager monitorProcessData:(PPBodyBaseModel *)model{
    self.currentWeightLabel.text = [UnitTool weightStrWithScaleName:manager.currentDevice.deviceName weightKg:model.weight / 100.0 andUnitType:self.currentUser.userUnit];
}

- (void)scaleManager:(PPScaleManager *)manager monitorLockData:(PPBodyFatModel *)model {
    PPDeviceModel *device = [manager currentDevice];
    DeviceModel *deviceModel = [[DeviceModel alloc] initWithPPDeviceModel:device];

    self.currentWeightLabel.text = [UnitTool weightStrWithScaleName:device.deviceName weightKg:model.ppWeightKg andUnitType:self.currentUser.userUnit];
    
    LFWeakSelf(self)
    if ([device.deviceName isEqualToString:kBLEDeviceHealthScale5] ||
        [device.deviceName isEqualToString:kBLEDeviceHealthScale6]) {
        NSString *message = [NSString stringWithFormat:@"Recive data %@",self.currentWeightLabel.text];
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"Tips" message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *matchAction = [UIAlertAction actionWithTitle:@"Config Wifi" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self addDevice:deviceModel];
            UINavigationController *nav = weakself.navigationController;
            [nav popViewControllerAnimated:NO];
            ConfigNetworkViewController *config = [ConfigNetworkViewController instance];
            config.device = deviceModel;
            [nav pushViewController:config animated:YES];
        }];

        UIAlertAction *nextAction = [UIAlertAction actionWithTitle:@"Later" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self addDevice:deviceModel];
            [weakself.navigationController popViewControllerAnimated:YES];
        }];
        UIAlertAction *notMyDataAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"Not main", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakself.scaleManager reStartSearching];

        }];
        [alertController addAction:matchAction];
        [alertController addAction:nextAction];
        [alertController addAction:notMyDataAction];
        [self presentViewController:alertController animated:YES completion:nil];
        
        
        
    }else{
        NSString * message = [NSString stringWithFormat:@"%@ %@ (%@)",self.currentWeightLabel.text,@" is your data? ",device.deviceName];
        UIAlertController * alertController = [UIAlertController alertControllerWithTitle:@"Tips" message:message preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"YES" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self addDevice:deviceModel];
            [weakself.navigationController popViewControllerAnimated:YES];

        }];
        
        UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"NO" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [weakself.scaleManager reStartSearching];
        }];
        [alertController addAction:cancleAction];
        [alertController addAction:okAction];
        [self presentViewController:alertController animated:NO completion:nil];
    }
}


- (void)monitorBluetoothWorkState:(PPBleWorkState)state{
    switch (state) {
        case PPBleWorkStateSearching:
            self.connectStateLabel.text = @"Scanning";
            break;
        case PPBleWorkStateSearchStop:
            self.connectStateLabel.text = @"Stop scanning";

            break;
        case PPBleWorkStateConnecting:
            self.connectStateLabel.text = @"Connecting";

            break;
        case PPBleWorkStateConnected:
            self.connectStateLabel.text = @"Connected";

            break;
        case PPBleWorkStateDisconnected:
            self.connectStateLabel.text = @"disconnected";
            [self.scaleManager reStartSearching];
            break;
    }
}

- (void)monitorBluetoothSwitchState:(CBManagerState)state API_AVAILABLE(ios(10.0)){
    if (state != CBManagerStatePoweredOn) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Please turn on Bluetooth first" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alertController dismissViewControllerAnimated:YES completion:nil];
        }];
        [alertController addAction:action];
        [self presentViewController:alertController animated:YES completion:nil];
    }


}

- (void)monitorBluetoothAuthorState:(CBManagerAuthorization)state API_AVAILABLE(ios(13.0)){
    if (state != CBManagerAuthorizationAllowedAlways) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Please enable the Bluetooth permissions first" message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [alertController dismissViewControllerAnimated:YES completion:nil];
        }];
        [alertController addAction:action];
        [self presentViewController:alertController animated:YES completion:nil];
    }
}


- (void)addDevice:(DeviceModel *)device{
    RLMRealm *realm = [RLMRealm defaultRealm];
    [realm transactionWithBlock:^{
        [realm addOrUpdateObject:device];
    }];
}

@end
